<template>
  <div class="content">
    <a-card :bordered="false" class="content-card">
      <div style="height: 14%">
        <div style="margin-top: 15px">
          <a-form
            :model="formState"
            name="horizontal_login"
            layout="inline"
            autocomplete="off"
            @finish="onFinish"
            :labelCol="{ style: 'width: 100px' }"
          >
            <a-form-item label="对象类型：" name="type">
              <a-select ref="select" v-model:value="formState.type" style="width: 200px">
                <a-select-option value="1">设备</a-select-option>
                <a-select-option value="2">管道</a-select-option>
                <a-select-option value="3">设备部件</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="公司名称：" name="companyName">
              <a-select
                ref="select"
                v-model:value="formState.companyName"
                style="width: 200px"
                label-in-value
                @change="handleChange"
                allowClear
              >
                <a-select-option
                  :key="item.companyCode"
                  v-for="item in companyData"
                  :value="item.companyCode"
                >
                  {{ item.companyName }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="车间名称：" name="dept">
              <a-select
                ref="select"
                v-model:value="formState.dept"
                style="width: 200px"
                label-in-value
                @change="handleChangeDept"
                allowClear
              >
                <a-select-option
                  :key="item.departmentCode"
                  v-for="item in workshopData"
                  :value="item.departmentCode"
                >
                  {{ item.departmentName }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="装置名称：" name="equ">
              <a-select
                ref="select"
                v-model:value="formState.equ"
                label-in-value
                style="width: 200px"
                @change="handleChangeEqu"
                allowClear
              >
                <a-select-option
                  :key="item.equipmentCode"
                  v-for="item in deviceData"
                  :value="item.equipmentCode"
                >
                  {{ item.equipmentName }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="对象名称：" name="objectName">
              <a-input style="width: 200px" allowClear v-model:value="formState.objectName">
              </a-input>
            </a-form-item>

            <a-form-item label="位号：" name="tag">
              <a-input style="width: 200px" allowClear v-model:value="formState.tag"> </a-input>
            </a-form-item>

            <a-form-item label="对象编码：" name="objCode">
              <a-input style="width: 200px" allowClear v-model:value="formState.objCode"> </a-input>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" html-type="submit" @click="queryBtn">查询</a-button>
              <a-button style="margin-left: 15px" @click="resetBtn">重置</a-button>
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="content-title">
        <div>
          <span class="content-title-text"> 腐蚀对象列表 </span>
          <a-button type="primary" style="margin-left: 15px">
            <template #icon>
              <PlusOutlined />
            </template>
            推算腐蚀对象
          </a-button>
          <a-button type="primary" style="margin-left: 15px" @click="batchConfirmation">
            批量确认
          </a-button>
        </div>
        <a-divider style="margin-top: 4px; margin-bottom: 20px"></a-divider>
      </div>
      <div class="content-bottom">
        <a-table
          :columns="columns"
          :data-source="tableData"
          :row-key="(r, i) => i"
          :row-selection="{ selectedRowKeys: selectedRowKeysData, onChange: onSelectChange }"
          :loading="loading"
          bordered
          :pagination="false"
          :scroll="{ x: 2700, y: 400 }"
          @resizeColumn="handleResizeColumn"
          :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <!-- && record.status != '已确认' -->
              <span>
                <a-button size="small" type="primary" @click="confirmRowBtn(record)"
                  >确认机理</a-button
                >
              </span>
            </template>
            <template v-if="column.dataIndex === 'type'">
              <span>
                {{ record.type == '1' ? '设备' : record.type == '2' ? '管道' : '设备部件' }}
              </span>
            </template>
            <template v-if="column.dataIndex === 'is_main'">
              <span>
                {{ record.is_main == '0' ? '否' : '是' }}
              </span>
            </template>
          </template>
        </a-table>
        <div class="content-bottom-pagination">
          <a-pagination
            v-model:current="page.page"
            v-model:pageSize="page.pageSize"
            :total="page.total"
            @showSizeChange="onShowSizeChange"
            @change="onChangePage"
          />
        </div>
      </div>
    </a-card>
    <ConfirmPop
      :isVisible="isVisible"
      @closeDialog="closeDialog"
      :corrosionSonData="corrosionSonData"
    />
  </div>
</template>

<script setup>
import {
  getCorrosive,
  getDictData,
  batchConfir,
  subTableTable
} from '@/assets/api/corrosion-api.js'
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import ConfirmPop from '@/views/confirmPop.vue'
// 根据唯一的 `id` 生成一个颜色映射
const colorMap = ref({})
const colors = ['#f2f', '#f43', '#d9d', '#f7c022', '#259645', '#f7c022'] // 定义一组颜色
const page = ref({
  current: 1,
  page: 1,
  pageSize: 10,
  total: 0
})
const formState = ref({
  type: '1',
  companyName: '',
  dept: '',
  equ: '',
  objectName: '',
  tag: '',
  objCode: ''
})
const tableData = ref([])
const selectedSaveKeys = ref([])
const loading = ref(false)
const columns = ref([
  {
    title: '操作',
    key: 'action',
    dataIndex: 'action',
    className: 'column-headColor',
    align: 'center',
    fixed: 'left',
    width: 100
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '车间',
    key: 'dept',
    dataIndex: 'dept',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    fixed: 'left',
    width: 100
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '装置',
    key: 'equ',
    dataIndex: 'equ',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    fixed: 'left',
    width: 100
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '对象类型',
    key: 'type',
    dataIndex: 'type',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    fixed: 'left',
    width: 100
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '对象ID',
    key: 'ref_id',
    dataIndex: 'ref_id',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    fixed: 'left',
    width: 100
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '位号',
    key: 'tag',
    dataIndex: 'tag',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    fixed: 'left',
    width: 100
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '名称',
    key: 'name',
    dataIndex: 'name',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    width: 100
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '材质',
    key: 'materialGrade',
    dataIndex: 'materialGrade',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    width: 100
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '腐蚀风险值',
    key: 'risk',
    dataIndex: 'risk',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    width: 100
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '腐蚀介质',
    key: 'medium',
    dataIndex: 'medium',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    width: 100
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '操作温度',
    key: 'temp',
    dataIndex: 'temp',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    width: 100
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '状态',
    key: 'status',
    dataIndex: 'status',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    width: 100
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '所属腐蚀回路',
    key: 'circuit',
    dataIndex: 'circuit',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    width: 120
    // customCell: (text) => {
    //   return {
    //     rowSpan: text.rowSpanId
    //   }
    // }
  },
  {
    title: '途径点编号',
    key: 'chNo',
    dataIndex: 'chNo',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    width: 120
  },
  {
    title: '途径点名称',
    key: 'chname',
    dataIndex: 'circuit',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    width: 120
  },
  {
    title: '是否腐蚀对象',
    key: 'ifno',
    dataIndex: 'ifno',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    width: 120
  },
  {
    title: '腐蚀机理名称',
    key: 'mechanism_name',
    dataIndex: 'mechanism_name',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    width: 120
  },
  {
    title: '是否主要腐蚀机理',
    key: 'is_main',
    dataIndex: 'is_main',
    resizable: true,
    className: 'column-headColor',
    align: 'center',
    width: 120
  }
])
onMounted(() => {
  getDict()
  getData()
})

function handleResizeColumn(w, col) {
  col.width = w
}
const selectedRowKeysData = ref([])
const onSelectChange = (selectedRowKeys) => {
  selectedRowKeysData.value = selectedRowKeys
  selectedSaveKeys.value = selectedRowKeys
}
function onFinish() {}
function batchConfirmation() {
  const idList = selectedSaveKeys.value.join(',')
  batchConfir(idList).then((res) => {
    if (res.success) {
      message.success('确认成功！')
      resetBtn()
    } else {
      message.error(res.error)
    }
  })
}
const isVisible = ref(false)
const corrosionSonData = ref([])
function confirmRowBtn(value) {
  subTableTable({
    id: value.id,
    page: 1,
    size: 9999
  }).then((res) => {
    if (res.success) {
      corrosionSonData.value = res.data
      isVisible.value = true
    } else {
      message.error(res.error)
    }
  })
}
function closeDialog() {
  isVisible.value = false
  getData()
}
const onShowSizeChange = (current, pageSize) => {
  page.value.page = current
  page.value.pageSize = pageSize
  getData()
}
const onChangePage = (pages, pageSize) => {
  page.value.page = pages
  page.value.pageSize = pageSize
  getData()
}
function queryBtn() {
  getData()
}
function getRowStyle(record) {
  const colorMap = {
    59935462: '#f0f5ff',
    59935463: '#fff7e6'
  }
  return {
    backgroundColor: colorMap[record.id] || '#ffffff'
  }
}
// const getRowClass = (record) => {
//   return {
//     'table-striped': true,
//     'custom-row-class': record.rowColor
//   }
// }
function getData() {
  loading.value = true
  getCorrosive({
    page: page.value.page,
    size: page.value.pageSize,
    type: formState.value.type,
    companyName: formState.value.companyName,
    dept: formState.value.dept,
    equ: formState.value.equ,
    objectName: formState.value.objectName,
    objCode: formState.value.objCode,
    tag: formState.value.tag
  }).then((res) => {
    if (res.success) {
      loading.value = false
      // tableData.value = res.data
      page.value.total = res.pagination.total
      const a = processData(res.data)
      // 给每个唯一的id分配颜色
      const updatedTableData = a.map((row, index) => {
        if (!colorMap.value[row.id]) {
          colorMap.value[row.id] = colors[index % colors.length]
        }
        // 使用Object.assign返回新对象
        return {
          ...row,
          rowColor: colorMap.value[row.id]
        }
      })
      // 手动触发响应性更新
      tableData.value = updatedTableData
    } else {
      loading.value = false
      message.error(res.error)
    }
  })
}
function resetBtn() {
  selectedSaveKeys.value = []
  selectedRowKeysData.value = []
  formState.value = {
    type: '1',
    companyName: '',
    dept: '',
    equ: '',
    objectName: '',
    tag: '',
    objCode: ''
  }
  selectDict.value = []
  companyMap.clear()
  companyData.value = []
  workshopMap.clear()
  workshopData.value = []
  deviceMap.clear()
  deviceData.value = []

  selectedSaveKeys.value = []
  selectedRowKeysData.value = []
  getDict()
  getData()
}

const selectDict = ref([])
const companyMap = new Map()
const companyData = ref([])

const workshopMap = new Map()
const workshopData = ref([])

const deviceMap = new Map()
const deviceData = ref([])
function getDict() {
  getDictData().then((res) => {
    if (res.success) {
      selectDict.value = res.data
      selectDict.value.forEach((item) => {
        companyMap.set(item.companyCode, item.companyName)
      })
      const result = Array.from(companyMap, ([companyCode, companyName]) => ({
        companyName,
        companyCode
      }))
      companyData.value = result

      // 车间
      selectDict.value.forEach((item) => {
        workshopMap.set(item.departmentCode, item.departmentName)
      })
      const resultDep = Array.from(workshopMap, ([departmentCode, departmentName]) => ({
        departmentCode,
        departmentName
      }))
      workshopData.value = resultDep

      // 装置
      selectDict.value.forEach((item) => {
        deviceMap.set(item.equipmentCode, item.equipmentName)
      })
      const resutDevice = Array.from(deviceMap, ([equipmentCode, equipmentName]) => ({
        equipmentCode,
        equipmentName
      }))
      deviceData.value = resutDevice
    }
  })
}

function handleChange(obj) {
  formState.value.dept = null
  formState.value.companyName = obj.label[0].children
  const arr = selectDict.value.filter((item) => item.companyCode === obj.value)
  // 车间
  workshopMap.clear()
  arr.forEach((item) => {
    workshopMap.set(item.departmentCode, item.departmentName)
  })
  const resultDep = Array.from(workshopMap, ([departmentCode, departmentName]) => ({
    departmentCode,
    departmentName
  }))
  workshopData.value = resultDep
}
function handleChangeDept(obj) {
  formState.value.dept = obj.label[0].children
  formState.value.equ = null
  const arr = selectDict.value.filter((item) => item.departmentCode === obj.value)
  // 装置
  deviceMap.clear()
  arr.forEach((item) => {
    deviceMap.set(item.equipmentCode, item.equipmentName)
  })
  const resutDevice = Array.from(deviceMap, ([equipmentCode, equipmentName]) => ({
    equipmentCode,
    equipmentName
  }))
  deviceData.value = resutDevice

  selectDict.value.forEach((item) => {
    if (item.departmentCode === obj.key) {
      formState.value.companyName = item.companyName
    }
  })
}

function handleChangeEqu(obj) {
  formState.value.equ = obj.label[0].children
  console.log(obj.key, '装置名称')
  selectDict.value.forEach((item) => {
    if (item.equipmentCode === obj.key) {
      formState.value.dept = item.departmentName
      formState.value.companyName = item.companyName
    }
  })
}

function processData(data) {
  const countMap = new Map()
  data.forEach((item) => {
    const currentCount = countMap.get(item.id) || 0
    countMap.set(item.id, currentCount + 1)
  })

  const result = []
  const addedIds = new Set()

  data.forEach((item) => {
    if (!addedIds.has(item.id)) {
      result.push({
        ...item,
        rowSpanId: countMap.get(item.id)
      })
      addedIds.add(item.id)
    } else {
      result.push({
        ...item,
        rowSpanId: 0
      })
    }
  })

  return result
}
</script>
<style scoped lang="scss">
:deep(.ant-table-tbody > tr > td) {
  padding: 3px !important;
}
:deep(.ant-table-thead > tr > th) {
  padding: 9px !important;
}
:deep(th.column-headColor) {
  background-color: #6c748d !important;
  color: #fff !important;
}

:deep(.ant-card-body) {
  padding: 15px;
  height: 100%;
}
:deep(.ant-table-thead > tr > th) {
  text-align: center !important;
}
.ant-form-item {
  margin-top: 15px;
}
:deep(.table-striped) td {
  background-color: #fafafa;
}
// .table-striped.custom-row-class {
//   background-color: var(--row-color);
// }
.custom-row-class {
  background-color: aquamarine;
}
.content {
  background-color: #edeff2;
  padding: 10px;
  height: 100%;
  &-card {
    background-color: #fff;
    height: 100%;
  }
  &-title {
    height: 5%;
    margin-top: 20px;
    &-text {
      font-size: 16px;
      font-weight: 600;
    }
  }
  &-bottom {
    margin-top: 20px;
    height: 70%;
    &-table {
      height: 95%;
      overflow: auto;
    }
    &-pagination {
      text-align: right;
      margin-top: 10px;
    }
  }
}
</style>
